﻿using System; 
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Reflection;
using System.Text;
using System.IO;

namespace StockMatch.Host.WindowsService
{
    public static class ServiceStarter
    {
        private static string startupFileName= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName); 
        public static void Start(ServiceBase service, ConsoleBase console, ServiceStartInfo serviceStartInfo, string[] args)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            if (console == null)
            {
                throw new ArgumentNullException("console");
            }
            if (serviceStartInfo == null)
            {
                throw new ArgumentNullException("serviceStartInfo");
            }
            if (string.IsNullOrEmpty(serviceStartInfo.ServiceName))
            {
                serviceStartInfo.ServiceName = service.ServiceName;
            }

            string command = "";
            if (args == null || args.Length == 0 || string.IsNullOrEmpty(args[0]))
            {
                command = serviceStartInfo.DefaultCommand;
            }
            else
            {
                command = args[0];
            }

            command = (command + "").Trim();
            if (command == serviceStartInfo.InstallCommand)
            {
                InstallService(serviceStartInfo);
            }
            else if (command == serviceStartInfo.RemoveCommand)
            {
                RemoveService(serviceStartInfo);
            }
            else if (command == serviceStartInfo.RunAsConsoleCommand)
            {
                StartAsConsole(console, serviceStartInfo);
            }
            else
            {
                StartAsService(service);
            }
        }

        /// <summary>
        /// 安装服务
        /// </summary> 
        private static void InstallService(ServiceStartInfo serviceStartInfo)
        { 
            bool bInstalledOk = ServiceInstaller.InstallService(startupFileName + (string.IsNullOrEmpty(serviceStartInfo.RunAsServiceCommand) ? "" : " " + serviceStartInfo.RunAsServiceCommand), serviceStartInfo);
            if (bInstalledOk)
            {
                StringBuilder sbNotice = new StringBuilder();
                sbNotice.AppendFormat("{0} Installed Successful.", serviceStartInfo.ServiceName);

                Console.WriteLine(sbNotice.ToString());
            }
            else
            {
                StringBuilder sbNotice = new StringBuilder();
                sbNotice.AppendFormat("{0} Installed Failure.", serviceStartInfo.ServiceName);

                Console.WriteLine(sbNotice.ToString());
            }
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        /// <summary>
        /// 删除服务
        /// </summary> 
        private static void RemoveService(ServiceStartInfo serviceStartInfo)
        {
            Console.WriteLine("If service is running,please stop it first.\r\n");
            bool bUninstalledOk = ServiceInstaller.UnInstallService(serviceStartInfo.ServiceName);
            if (bUninstalledOk)
            {
                StringBuilder sbNotice = new StringBuilder();
                sbNotice.AppendFormat("{0} Removed Successful.", serviceStartInfo.ServiceName);

                Console.WriteLine(sbNotice.ToString());
            }
            else
            {
                StringBuilder sbNotice = new StringBuilder();
                sbNotice.AppendFormat("{0} Removed Failure.", serviceStartInfo.ServiceName);

                Console.WriteLine(sbNotice.ToString());
            }
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        /// <summary>
        /// 以服务运行
        /// </summary>
        private static void StartAsService(ServiceBase service)
        {
            ServiceBase.Run(service);
        }

        /// <summary>
        /// 以控制台运行
        /// </summary>
        private static void StartAsConsole(ConsoleBase console, ServiceStartInfo serviceStartInfo)
        {
            StringBuilder sbNotice = new StringBuilder();
            sbNotice.AppendFormat("{0}\r\n", startupFileName);
            sbNotice.AppendFormat("{0}\tTo Install The Service.May need to run as administrator.\r\n", serviceStartInfo.InstallCommand);
            sbNotice.AppendFormat("{0}\tTo Remove The Service.May need to run as administrator.\r\n", serviceStartInfo.RemoveCommand);
            sbNotice.AppendFormat("{0}\tTo Run As A Console App For Debugging.\r\n", serviceStartInfo.RunAsConsoleCommand);
            sbNotice.AppendFormat("{0}\tTo Run As A Service.\r\n", serviceStartInfo.RunAsServiceCommand);
            sbNotice.AppendFormat("Default command is {0}.\r\n", serviceStartInfo.DefaultCommand);
            sbNotice.Append(new string('-', 70));
            Console.WriteLine(sbNotice.ToString());

            console.Start();
        }
    }
}
